package com.zzq.service.v1.impl;

import com.zzq.config.K8sInit;
import com.zzq.service.v1.PodService;
import io.kubernetes.client.ApiClient;
import io.kubernetes.client.ApiException;
import io.kubernetes.client.apis.CoreV1Api;
import io.kubernetes.client.custom.Quantity;
import io.kubernetes.client.models.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PodServiceImpl implements PodService {


    @Autowired
    private K8sInit k8sInit;

    @Override
    public void createPod() {

        ApiClient client = k8sInit.getConnection();
        CoreV1Api apiInstance = new CoreV1Api(client);

        // 构建选择器
        Map<String, String> selectLabels = new HashMap<>();
        String name = "162-3";
        selectLabels.put("deploy", name);

        // 容器暴漏端口
        List<V1ContainerPort> portList = Arrays.asList(
                new V1ContainerPort().containerPort(8080).protocol("TCP")
        );

        // 资源限制map,--默认会转换成字节
        HashMap<String, Quantity> limitsMap = new HashMap<>();
        limitsMap.put("memory", new Quantity("4Gi"));
        HashMap<String, Quantity> requestsMap = new HashMap<>();
        requestsMap.put("memory", new Quantity("4Gi"));

        // 构建Pod
        V1Pod body = new V1Pod()
                .metadata(new V1ObjectMeta()
                        .name(name) // 名称
                        .namespace("default")   //命名空间
                        .labels(selectLabels))
                .spec(new V1PodSpec()
                        .containers(Arrays.asList(new V1Container()
                                .name("nginxPod")   // 容器名称
                                .image("nginx:latest")   // 镜像名称
                                .imagePullPolicy("IfNotPresent")   // 镜像拉取策略
                                .ports(portList)    //对外暴漏接口
                                .volumeMounts(Arrays.asList(new V1VolumeMount()
                                        .name("声明挂载名称-同下")
                                        .mountPath("挂载到容器内执行目录")))
                                .resources(new V1ResourceRequirements()
                                        .limits(limitsMap)  //限制参数，构建在上面
                                        .requests(requestsMap))  //限制参数，构建在上面
                                .livenessProbe(new V1Probe()
                                        .exec(new V1ExecAction()
                                                .command(Arrays.asList("/bin/sh", "-c", "shell执行结果"))   // 存活探针-shell方式
                                        )
                                        .initialDelaySeconds(300)   // 启动后等待/秒
                                        .periodSeconds(60)         // 探测的时间间隔/秒
                                        .failureThreshold(1)        // 失败次数
                                )
                        ))
                        .restartPolicy("Never") // pod重启策略
                        .volumes(Arrays.asList(new V1Volume()
                                .name("声明挂载名称-同上")
                                .hostPath(new V1HostPathVolumeSource()
                                        .path("宿住机目录"))))   //需挂载宿住机的目录结构
                );


        //定义返回结果
        Map<String, String> messages = new HashMap<>();
        try {
            V1Pod result = apiInstance.createNamespacedPod("default", body, null, null, null);
        } catch (ApiException e) {
            if (e.getCode() == 409) {
                messages.put("error", "Pod创建已重复！");
            } else if (e.getCode() == 200) {
                messages.put("success", "Pod创建成功！");
            } else if (e.getCode() == 201) {
                messages.put("error", "Pod创建已重复！");
            } else if (e.getCode() == 401) {
                messages.put("error", "无权限操作！");
            } else {
                messages.put("error", "Pod创建失败！");
            }
        }

        System.out.println("最终结果----" + messages);

    }


    @Override
    public void updatePod() {

    }

    @Override
    public V1Pod getPodDetail() {
        return null;
    }

    @Override
    public void deletePod() {

    }
}
